import React, {createContext, useEffect, useState} from 'react';
import {createNativeStackNavigator} from '@react-navigation/native-stack';
import BottomTabsNavigator from '../Tabs/BottomTabsNavigator';
import DetailScreen from '../Screens/Details';
import LoginScreen from '../Screens/Login';
import RegisterScreen from '../Screens/Register';
import StorageManager from '../Storage/StorageManager';
import {Alert} from 'react-native';

const Stack = createNativeStackNavigator();

type ContextType = {
  login: boolean;
  setLogin: React.Dispatch<React.SetStateAction<boolean>>;
};
export const LoginContext = createContext<ContextType>({} as ContextType);

const HomeStack = () => {
  const [login, setLogin] = useState(false);

  useEffect(() => {
    StorageManager.readObject('Login')
      .then(([success, value]) => {
        if (success && value == '1') {
          if (!login) {
            setLogin(true);
          } else {
            if (login) {
              setLogin(false);
            }
          }
        }
      })
      .catch(() => {
        Alert.alert('Oops! Read login state error.');
      });
  }, []);

  return (
    <LoginContext.Provider value={{login, setLogin}}>
      <Stack.Navigator
        initialRouteName="BottomTabsNavigator"
        screenOptions={options.screenOptions}>
        <Stack.Screen
          name="BottomTabsNavigator"
          component={BottomTabsNavigator}
          options={options.navigatorOptions}
        />
        <Stack.Screen
          name="Detail"
          component={DetailScreen}
          options={options.detailOption}
        />
        <Stack.Screen
          name="Login"
          component={LoginScreen}
          options={options.detailOption}
        />
        <Stack.Screen
          name="Register"
          component={RegisterScreen}
          options={options.detailOption}
        />
      </Stack.Navigator>
    </LoginContext.Provider>
  );
};

const options = {
  screenOptions: {
    headerTintColor: 'black',
    headerBackTitleVisible: false,
  },
  navigatorOptions: {
    headerShown: false,
  },
  detailOption: {
    // title : '详情'
  },
};

export default HomeStack;
